package com.mifengs.mall.ui.web;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.Callback;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.entity.JsCallAppFunction;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.ui.hxcec.CecLoginActivity;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.ui.login.NewRegisterActivity;
import com.mifengs.mall.ui.main.MainActivity;
import com.mifengs.mall.ui.my.RedPacketActivity;
import com.mifengs.mall.ui.opencompany.ShopTypeActivity;
import com.mifengs.mall.ui.openself.MaterialSubFragment;
import com.mifengs.mall.util.PayWayUtils;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.widget.MyWebView;
import com.trello.rxlifecycle.android.FragmentEvent;
import com.trello.rxlifecycle.components.support.RxFragment;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.ResponseBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lihaoqi on 2017/11/28.
 */

public class WebFrgPresent implements WebFrgContract.Presenter {

    private final WebFrgContract.View mView;
    public WebFrgPresent(WebFrgContract.View mView) {
        this.mView = mView;
    }

    private Activity getActivity(){
        return mView.getActivity();
    }


    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

    @Override
    public void loadJs() {
        final MyWebView myWebView = mView.getWebView();
        //loadJsToSetTitle();

        myWebView.evaluateJavascript("javascript:openWithSameWindow()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if (!TextUtils.isEmpty(value) && (!value.equals("null"))) {
                    if (value.equals("true")) {
                        mView.setIsRealTabPage(true);  // 因为重定向原因等等看不懂就算了 烂摊子
                    }
                }
                mView.setSwipeEnableTrue();
            }
        });

        myWebView.evaluateJavascript("javascript:getShareUrl()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if (!TextUtils.isEmpty(value) && (!value.equals("null"))) {
                    int s = value.length();
                    String url = value.substring(1, s - 1);
                    if (getActivity() instanceof CommonWebActivity) {
                        ((CommonWebActivity) getActivity()).setShare(url,"","",1,"",false,"");
                    }
                }
            }
        });


        myWebView.evaluateJavascript("javascript:isNeedTopBar()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if(getActivity() instanceof CommonWebActivity){
                    if(value.equals("true")){
                        ((CommonWebActivity) getActivity()).setTopBarGone();
                    }else{
                        ((CommonWebActivity) getActivity()).setTopBarVisible();
                    }
                }
            }
        });

        myWebView.evaluateJavascript("javascript:isBackToFinish()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if(getActivity() instanceof CommonWebActivity){
                    if(value.equals("true")){
                       mView.isBackToFinish(true);
                    }else{
                       mView.isBackToFinish(false);
                    }
                }
            }
        });

    }

    @Override
    public void loadJsToSetTitle() {
        MyWebView myWebView = mView.getWebView();
        myWebView.evaluateJavascript("javascript:getAppTitle()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                if (!TextUtils.isEmpty(value) && (!value.equals("null"))) {
                    if (getActivity() instanceof CommonWebActivity) {
                        int s = value.length();
                        String va = value.substring(1, s - 1);
                        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
                            ((CommonWebActivity) getActivity()).setTitle(va);
                        }else{
                            ((CommonWebActivity) getActivity()).setTitle(unicodeToString(va));
                        }
                    }
                }
            }
        });
    }


    @Override
    public boolean handleOperation(String url) {
        Uri uri = Uri.parse(url);
        String operation = uri.getHost();
        MyWebView webView = mView.getWebView();
        if (operation.equals("goHomePage")) {
            if(getActivity() instanceof CommonWebActivity){
                getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
                mView.finish();
            }
            EventBus.getDefault().post(new MainEvent(MainEvent.TOHOMEPAGE));
        }else if(operation.equals("refreshPage")){
            webView.reload();
        }else if(operation.equals("logout")){
            logoutClean();
            logout();
        }else if(operation.equals("goback")){
            if(getActivity() instanceof CommonWebActivity){
                ((CommonWebActivity)getActivity()).goback();
            }else{
                if(mView.getWebView()!=null){
                    mView.getWebView().goBack();
                }
            }
        }else if(operation.equals("getHxOrderInfo")){
            getHxOrderInfo(uri);
        }else if(operation.equals("getShareObj")){
            getShareInfo(uri);
        } else if(operation.equals("goShopcart")){
//            if(getActivity() instanceof CommonWebActivity){
//                getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
//                mView.finish();
//            }
//            EventBus.getDefault().post(new MainEvent(MainEvent.TOSHOPCART));
            ToIntentUtil.toCommonIntent(Constant.H5_CART,mView.getContext());
        }else if(operation.equals("login")){
            if(getActivity() instanceof CommonWebActivity){
                getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                mView.finish();
            }
        }else if(operation.equals("register")){
            if(getActivity() instanceof CommonWebActivity){
                getActivity().startActivity(new Intent(getActivity(), NewRegisterActivity.class));
                mView.finish();
            }
        }else if (operation.equals("pay")){
            if(getActivity() instanceof CommonWebActivity){
                getPayInfo(uri);
            }
        }else if(operation.equals("myRedPacket")){
            getActivity().startActivity(new Intent(getActivity(), RedPacketActivity.class));
        }else if(operation.equals("goBackWithdrawal")){
            goBackWithdrawal(uri);
        }else if(operation.equals("setUpStore")){
            if(getActivity() instanceof CommonWebActivity){
                getActivity().startActivity(new Intent(getActivity(), ShopTypeActivity.class));
                mView.finish();
            }
        }else if(operation.equals("getContacts")){
            mView.getContactsInfo();
        }else if(operation.equals("jsCallAppFunction")){
            handleJsCallAppFunction(url);
        }
        return true;
    }

    private void handleJsCallAppFunction(String url) {
        String[] paramer=url.split("#");
        JsCallAppFunction jsCallAppFunction = new Gson().fromJson(paramer[1].toString(),JsCallAppFunction.class);
//        if(jsCallAppFunction.getIsReturn()== 1){
//            mView.getJsCallAppFunction(jsCallAppFunction);
//        }
        String functionName = jsCallAppFunction.getFunctionName();
        if(functionName.equals("getLocation")){
            mView.getLocation(jsCallAppFunction.getIsReturn());
        }
    }

    private void JsCallBack(){

    }


    private void goBackWithdrawal(Uri uri){
        String predepositUrl = uri.getQueryParameter("predepositUrl");
        String withdrawalUrl = uri.getQueryParameter("withdrawalUrl");
        mView.goBackWithdrawal(predepositUrl,withdrawalUrl);
    }

    private void getPayInfo(Uri uri) {
        String type = uri.getQueryParameter("type");
        String orderId = uri.getQueryParameter("orderId");
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("subIds",orderId);
        hashMap.put("payTypeId",type);
        if(!TextUtils.isEmpty(PreferenceUtils.getToken())){
            hashMap.put("app_token",PreferenceUtils.getToken());
        }
        PayWayUtils payWayUtils = new PayWayUtils(getActivity());
        MyWebView myWebView = mView.getWebView();
        CookieManager cookieManager = CookieManager.getInstance();
        String url = myWebView.getUrl();
        //String cookieStr = cookieManager.getCookie(url);
        String cookieStr = "";
        if("ALP".equals(type)){
            ZhiFuBao(hashMap,payWayUtils,cookieStr);
        }else if("WX".equals(type)){
            WeiXin(hashMap,payWayUtils,cookieStr);
        }
    }

    @Override
    public void payClose(){
        final MyWebView myWebView = mView.getWebView();
        //loadJsToSetTitle();
//        myWebView.evaluateJavascript("javascript:payResult()", new ValueCallback<String>() {
//            @Override
//            public void onReceiveValue(String value) {
//
//            }
//        });
        myWebView.loadUrl("javascript:payResult()");
    }

    @Override
    public void saveContactsInfo() {
//        OkHttpClient okHttpClient = new OkHttpClient();
//        RequestBody requestBody = new FormBody.Builder()
//                .add("contactsInfo", "这四十分钟酸")
//                .add("app_token", PreferenceUtils.getToken())
//                .build();
//        Request request = new Request.Builder()
//                .url("http://192.168.0.132:8081/p/saveContactsInfo.do")
//                .post(requestBody)
//                .build();
//        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                ToastUitl.show(e.getMessage(), Toast.LENGTH_SHORT);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Log.d("1111", "onResponse: " + response.body().string());
//                ToastUitl.show("请求成功", Toast.LENGTH_SHORT);
//            }
//        });


//
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("contactsInfo",mView.contactsInfo());
        hashMap.put("app_token", PreferenceUtils.getToken());
//        mView.showLoading();
        NetWork.getHomeDataApi().updateContact(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBody>bindToLife())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        mView.hideLoading();
                        mView.showNetError();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        mView.hideLoading();
                        String result = null;
                        try {
                            result = responseBody.string();
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getString("status").equals("0000")) {
//                                ToastUitl.show("上次成功", Toast.LENGTH_SHORT);
                                PreferenceUtils.saveContacts(getActivity(),"1");
                            }else{
//                                ToastUitl.show(jsonObject.getString("info"), Toast.LENGTH_SHORT);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void WeiXin(HashMap<String, String> hashMap, PayWayUtils payWayUtils,String cookieStr) {
        mView.showLoading();
        NetWork.getOrderPayApi().pay(cookieStr,hashMap)
                .flatMap(payWayUtils.getPayFunc1())
                .flatMap(payWayUtils.getRechargeWeiXinFunc1())
                .subscribeOn(Schedulers.io())
                .compose(((RxFragment)mView).<String>bindUntilEvent(FragmentEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.showLong(e.toString());
                        mView.hideLoading();
                    }

                    @Override
                    public void onNext(String s) {
                        mView.hideLoading();
                    }
                });
    }

    private void ZhiFuBao(HashMap<String, String> hashMap, PayWayUtils payWayUtils,String cookieStr) {
               // String token =  PreferenceUtils.getToken();
                mView.showLoading();
                NetWork.getOrderPayApi().pay(cookieStr,hashMap)
                        .flatMap(payWayUtils.getPayFunc1())
                        .flatMap(payWayUtils.getRechargeZfbFunc1())
                        .subscribeOn(Schedulers.io())
                        .compose(((RxFragment)mView).<String>bindUntilEvent(FragmentEvent.DESTROY))
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<String>(){

                            @Override
                            public void onCompleted() {
                                mView.hideLoading();
                            }

                            @Override
                            public void onError(Throwable e) {
                                mView.hideLoading();
                                ToastUitl.showLong(e.getMessage());
                            }

                            @Override
                            public void onNext(String s) {
                                mView.hideLoading();
                                payClose();
                            }
                        });
    }

    private void getShareInfo(Uri uri){
        String url = uri.getQueryParameter("url");
        String shareId = uri.getQueryParameter("shareId");
        String img = uri.getQueryParameter("img");
        String prod = uri.getQueryParameter("prod");
        String logId = uri.getQueryParameter("logId");
        String title = uri.getQueryParameter("title");
        String id = uri.getQueryParameter("id");
        String shareTopText = uri.getQueryParameter("shareTopText");
        boolean isGoodsShare = uri.getBooleanQueryParameter("isGoodsShare",false);
        if (getActivity() instanceof CommonWebActivity) {
            ((CommonWebActivity) getActivity()).setShare(url+"?shareId="+shareId+"&logId="+logId+"&id="+id,img,prod,2,title,isGoodsShare,shareTopText);
        }
    }

    private void getHxOrderInfo(Uri uri) {
        boolean isLogin = PreferenceUtils.getLoginStatus();
        if (isLogin) {
            String orderId = uri.getQueryParameter("id");
            String orderName = uri.getQueryParameter("name");
            String orderPrice = uri.getQueryParameter("price");
            String orderImg = uri.getQueryParameter("img");
            String orderUrl = uri.getQueryParameter("url");
            String photoUrl = PreferenceUtils.getPhotoUrl(getActivity());
            Intent intent = new Intent(getActivity(), CecLoginActivity.class);
            intent.putExtra("orderName",orderName);
            intent.putExtra("orderPrice",orderPrice);
            intent.putExtra("orderImg",photoUrl+orderImg);
            intent.putExtra("orderUrl",orderUrl);
            intent.putExtra("orderId",orderId);
            getActivity().startActivity(intent);
        } else {
            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
        }

    }


    @Override
    public void logout() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("app_token", PreferenceUtils.getToken());
//        mView.showLoading();
        NetWork.getLoginApi().logout(PreferenceUtils.getToken(),map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
//                        mView.hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean tokenBeanResponseBean) {
//                        mView.hideLoading();
                        String status = tokenBeanResponseBean.getStatus();
                        if (status.equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("账号退出成功，请重新登录！",Toast.LENGTH_SHORT);
                        }else{
//                            ToastUitl.show(tokenBeanResponseBean.getInfo(),Toast.LENGTH_SHORT);
                        }

                    }
                });
    }

    private void logoutClean() {
        PreferenceUtils.clearLoginInfo();
        mView.getWebView().cleanCookie();
        EventBus.getDefault().post(new MainEvent(MainEvent.TOHOMEPAGE));
        EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
        PreferenceUtils.saveBooleanPreference(mView.getContext(), MaterialSubFragment.IS_SAVE,false);
        try {
            if (ChatClient.getInstance().isLoggedInBefore()) {
                ChatClient.getInstance().logout(true, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
            }
        }catch (Exception e){
            Log.e("ChatClient",e.toString());
        }
        getActivity().startActivity(new Intent(getActivity(),LoginActivity.class));
    }





}